package com.siants;

import com.siants.model.FileStatus;
import com.sun.javafx.scene.control.skin.VirtualFlow;
import com.sun.org.apache.xpath.internal.axes.IteratorPool;
import org.tmatesoft.svn.core.SVNException;
import org.tmatesoft.svn.core.SVNURL;
import org.tmatesoft.svn.core.internal.io.svn.SVNRepositoryFactoryImpl;
import org.tmatesoft.svn.core.internal.wc.DefaultSVNOptions;
import org.tmatesoft.svn.core.wc.*;

import java.io.*;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

/**
 * Created by yanxin on 2017/6/21.
 */
public class SVNList {

    private static SVNClientManager ourClientManager;

    private List<File> filelist = new ArrayList<File>();


    /**
     *
     * @param svnUrl
     * @param name
     * @param password
     * @param fileUrl
     * @return
     */
    public List<FileStatus> getSVNStatusList(String svnUrl, String name, String password, String fileUrl){
        SVNRepositoryFactoryImpl.setup();

        SVNURL repositoryURL = null;
        List<FileStatus> fileStatusList = new ArrayList<FileStatus>();
        try {
            repositoryURL = SVNURL.parseURIEncoded(svnUrl);
        } catch (SVNException e) {
            e.printStackTrace();
        }

        ISVNOptions options = SVNWCUtil.createDefaultOptions(true);
        ourClientManager = SVNClientManager.newInstance((DefaultSVNOptions) options, name,password);

        SVNStatusClient client = ourClientManager.getStatusClient();
        List<File>  files = getFileList(fileUrl);

        List<String> ignores = getIgnoreFiles("/ignorefile.txt");
        //调用忽略处理方法，忽略无用file
        files = ignoreFile(files,ignores);
        for (File file : files){
            FileStatus fileStatus = getSVNStatus(file, client);
            if(!SVNStatusType.STATUS_NORMAL.toString().equals(fileStatus.getSVNStatus())){
                fileStatusList.add(fileStatus);
            }

        }
        return fileStatusList;
    }

    private FileStatus getSVNStatus(File file, SVNStatusClient client) {
        FileStatus fileStatus = new FileStatus();
        try {
            SVNStatus svnStatus =  client.doStatus(file,false);
            fileStatus.setFilePath(file.getPath());
            fileStatus.setFileName(file.getName());
            fileStatus.setSVNStatus(svnStatus.getNodeStatus().toString());
        } catch (SVNException e) {
            e.printStackTrace();
        }
        return fileStatus;
    }

    public List<File> getFileList(String strPath) {
        File dir = new File(strPath);
        File[] files = dir.listFiles(); // 该文件目录下文件全部放入数组

        if (files != null) {
            for (int i = 0; i < files.length; i++) {
                String fileName = files[i].getName();
                if(!"target".equals(fileName) && !".svn".equals(fileName)){
                    if (files[i].isDirectory() ) { // 判断是文件还是文件夹
                        getFileList(files[i].getAbsolutePath()); // 获取文件绝对路径
                    }else if(!fileName.endsWith("iml")){ //排除特殊结尾的 idea增加的iml文件
                        //String strFileName = files[i].getAbsolutePath();
                        //System.out.println("---" + strFileName);
                        filelist.add(files[i]);
                    }
                }
            }

        }
        return filelist;
    }

    public static void writeFile(List<FileStatus> fileStatusList, String fileName) {
        File file = new File(fileName);
        try {
            BufferedWriter bw = new BufferedWriter(new FileWriter(file, true));
           //BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file,false), "UTF-8"));
            for (FileStatus fileStatus : fileStatusList) {
                bw.write(fileStatus.getFilePath() +","+fileStatus.getSVNStatus() + "\r\n");
            }
            bw.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public List<File> ignoreFile(List<File> files, List<String> ignores){
        List<File> returnFile = new ArrayList<File>();
        Iterator<File> fileIterator = files.iterator();
        boolean flag;
        while (fileIterator.hasNext()){
            File file = fileIterator.next();
            flag = true;
            Iterator<String> ignoresIterator = ignores.iterator();
            while (ignoresIterator.hasNext()){
                String ignore = ignoresIterator.next();
                if(file.getName().equals(ignore)){
                    fileIterator.remove();
                    flag = false;
                    break;
                }
            }
            if(flag == true){
                returnFile.add(file);
            }
        }
        return returnFile;
    }

    public List<String> getIgnoreFiles(String pathname){
        List<String> ignoreFiles = new ArrayList<String>();
        try {
            InputStreamReader reader = new InputStreamReader(this.getClass().getResourceAsStream(pathname));  // 建立一个输入流对象reader
            BufferedReader br = new BufferedReader(reader); // 建立一个对象，它把文件内容转成计算机能读懂的语言
            String line = "";
            while (line != null) {
                line = br.readLine(); // 一次读入一行数据
                if(line != null ){
                    ignoreFiles.add(line);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ignoreFiles;
    }

}
